#include "gui_keyboard.h"
#include "gui_entry.h"
#include <stdio.h>
#include <string.h>
#include <uview.h>

int gui_keyboard_filter(int keycode, int modify)
{
    keycode = uview_keypad2ascii(keycode);
    switch (keycode)
    {
    case UVIEW_KEY_NUMLOCK:
    case UVIEW_KEY_CAPSLOCK:
    case UVIEW_KEY_SCROLLOCK:
    case UVIEW_KEY_RSHIFT:
    case UVIEW_KEY_LSHIFT:
    case UVIEW_KEY_RCTRL:
    case UVIEW_KEY_LCTRL:
    case UVIEW_KEY_RALT:
    case UVIEW_KEY_LALT:
        return 0;
    default:
        break;
    }
    return keycode;
}

int gui_keyboard_keydown(gui_spirit_t *spirit, int keycode, int modify)
{
    gui_container_t *container = spirit->container;
    if (!container)
        return -1;
    gui_spirit_t *tmp;
    list_traversal_all_owner_to_next(tmp, &container->children_list, list)
    {
        if (!tmp->visiable)
            continue;
        switch (tmp->type)
        {
        case GUI_SPIRIT_TYPE_LABEL:
            break;
        case GUI_SPIRIT_TYPE_BUTTON:
            break;
        case GUI_SPIRIT_TYPE_ENTRY:
        {
            gui_entry_t *entry = GUI_ENTRY(tmp);
            if (entry->focus)
            {
                keycode = gui_keyboard_filter(keycode, modify);   
                dprintf("[gui_keyborad] debug: key ascii %d modify %d\n",keycode,modify);

                if (!keycode)
                    break;
                gui_entry_process_key(entry, keycode, modify);
            }
        }
        break;
        default:
            break;
        }

        // spirit had sub contianer
        if (spirit->container)
        {
            gui_spirit_t *sub_spirit = &spirit->container;
            list_traversal_all_owner_to_next(sub_spirit, &spirit->container->children_list, list)
            {
                gui_keyboard_keydown(sub_spirit, keycode, modify);
            }
        }
    }
    return -1;
}

int gui_keyboard_keyup(gui_spirit_t *spirit, int keycode, int modify)
{
    gui_container_t *container = spirit->container;
    if (!container)
        return -1;
    gui_spirit_t *tmp;
    list_traversal_all_owner_to_next(tmp, &container->children_list, list)
    {
        if (!tmp->visiable)
            return -1;
        switch (tmp->type)
        {
        case GUI_SPIRIT_TYPE_LABEL:
            break;
        case GUI_SPIRIT_TYPE_BUTTON:
            break;
        default:
            break;
        }

        // spirit had sub contianer
        if (spirit->container)
        {
            gui_spirit_t *sub_spirit = &spirit->container;
            list_traversal_all_owner_to_next(sub_spirit, &spirit->container->children_list, list)
            {
                gui_keyboard_keyup(sub_spirit, keycode, modify);
            }
        }
    }
    return -1;
}
